package com.ruoyi.wechat.service.impl;

import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.wechat.service.WeChatUserService;
import com.ruoyi.wechat.util.CommonUtil;
import com.ruoyi.wechat.util.ConstantWeChat;
import com.ruoyi.wechat.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import com.alibaba.fastjson.JSONObject;
@Service
public class WeChatUserServiceImp implements WeChatUserService {
	@Autowired
	private ISysConfigService sysConfigService;
	@Autowired
	private TokenUtil tokenUtil;
	@Override
	public JSONObject getWeChatUserInfo(String openid,String APPKEY) {
		// TODO Auto-generated method stub
		if(openid==null){
			openid="";
		}
		JSONObject job= CommonUtil.doGetURL(ConstantWeChat.GETWECHATUSERINFO.replace("#ACCESS_TOKEN#", tokenUtil.getToken(APPKEY).getAccessToken()).replace("#OPENID#", openid));
		String errcode=job.getString("errcode");
		if(null!=errcode){
			job= CommonUtil.doGetURL(ConstantWeChat.GETWECHATUSERINFO.replace("#ACCESS_TOKEN#", tokenUtil.getToken(APPKEY,true).getAccessToken()).replace("#OPENID#", openid));
		}
		return job;
	}
	@Override
	public JSONObject converWechatOpenId(String code,String APPKEY) {
		String appId = sysConfigService.selectConfigByKey(APPKEY+"_APPKEY");
		String appSecret = sysConfigService.selectConfigByKey(APPKEY+"_SECRET");
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
				"appid=" + appId + "&" +
				"secret=" + appSecret + "&" +
				"code=" + code + "&" +
				"grant_type=authorization_code";
		String content = HttpUtils.doGet(url, "UTF-8", 100, 1000);
		// System.out.println("C端用户"+content);
		return JSONObject.parseObject(content);
	}

}
